<template>
  <div class="post-container">
    <h2>发布新帖</h2>
    <el-form label-width="80px">
      <el-form-item label="类别">
        <el-select v-model="categoryId" placeholder="请选择类别" style="width: 220px;">
          <el-option v-for="cat in categories" :key="cat.id" :label="cat.name" :value="cat.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="标题">
        <el-input v-model="title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="简介">
        <el-input v-model="descr" type="textarea" placeholder="请输入简介" rows="2" />
      </el-form-item>
      <el-form-item label="标签">
        <el-tag
          v-for="tag in dynamicTags"
          :key="tag"
          class="mx-1"
          closable
          :disable-transitions="false"
          @close="handleTagClose(tag)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="tagInputVisible"
          ref="InputRef"
          v-model="tagInputValue"
          class="ml-1 w-20"
          size="small"
          @keyup.enter="handleTagInputConfirm"
          @blur="handleTagInputConfirm"
        />
        <el-button v-else class="button-new-tag ml-1" size="small" @click="showTagInput">
          + 添加标签
        </el-button>
      </el-form-item>
      <el-form-item label="封面">
        <el-upload
          class="cover-uploader"
          action="/api/user/common/upload"
          :show-file-list="false"
          :before-upload="beforeCoverUpload"
          :on-success="handleCoverSuccess"
          :auto-upload="true"
          name="file"
          :headers="uploadHeaders"
        >
          <img v-if="coverUrl" :src="coverUrl" class="cover-preview" />
          <el-button v-else>上传封面</el-button>
        </el-upload>
        <div class="avatar-upload-tips">
          <div>图片大小不超过2M</div>
          <div>仅能上传 PNG JPEG JPG类型图片</div>
          <div>建议上传200*200或300*300尺寸的图片</div>
        </div>
      </el-form-item>
      <el-form-item label="内容">
        <el-input v-model="content" type="textarea" :rows="10" placeholder="请输入正文内容" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlePublish">发布</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElInput } from 'element-plus'
import { getToken } from '@/utils/auth'

const InputRef = ref<InstanceType<typeof ElInput>>()
const dynamicTags = ref<string[]>([])
const tagInputVisible = ref(false)
const tagInputValue = ref('')

const categories = [
  { id: 1, name: '角色讨论' },
  { id: 2, name: '副本攻略' },
  { id: 3, name: '剧情解析' },
  { id: 4, name: '同人创作' },
  { id: 5, name: '赛事资讯' }
]
const categoryId = ref()
const title = ref('')
const descr = ref('')
const coverUrl = ref('')
const content = ref('')

const handleTagClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const showTagInput = () => {
  tagInputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleTagInputConfirm = () => {
  if (tagInputValue.value) {
    dynamicTags.value.push(tagInputValue.value)
  }
  tagInputVisible.value = false
  tagInputValue.value = ''
}

const uploadHeaders = computed(() => ({
  token: getToken() || ''
}))

function beforeCoverUpload(file: File) {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) {
    ElMessage.error('只能上传 PNG/JPEG/JPG 格式图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

function handleCoverSuccess(response: any) {
  coverUrl.value = response.data
}

async function handlePublish() {
  if (!categoryId.value || !title.value || !descr.value || !content.value) {
    ElMessage.error('请填写完整信息')
    return
  }
  const data = {
    categoryId: categoryId.value,
    title: title.value,
    descr: descr.value,
    cover: coverUrl.value || '没有',
    content: content.value,
    tags: dynamicTags.value.join(',')
  }
  try {
    await request.post('/user/blog', data)
    ElMessage.success('发布成功')
    categoryId.value = ''
    title.value = ''
    descr.value = ''
    coverUrl.value = ''
    content.value = ''
    dynamicTags.value = []
  } catch (e) {
    // 错误信息已由拦截器处理
  }
}
</script>

<style scoped>
.cover-preview {
  width: 120px;
  height: 80px;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid #eee;
  margin-bottom: 8px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.w-20 {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style> 